// 顶点着色器
const vss_s = `
  attribute vec4 a_Position;
  uniform mat4 u_xformMatrix;
  void main() {
    gl_Position = u_xformMatrix * a_Position;
  }
`;
// 片元着色器
const fs_s = `
  void main() {
    gl_FragColor = vec4(1, 0, 0, 1);
  }
`;

function main() {
  const canvas = document.getElementById('webgl');
  if (!canvas) {
    alert('Field to get element by id: webgl');
    return false;
  }
  const gl = getWebGLContext(canvas);
  if (!gl) {
    alert('Field to get webgl by canvas');
    return false;
  }
  if (!initShaders(gl, vss_s, fs_s)) {
    alert('Field to init shaders.');
    return false;
  }
  const pointCount = initVertexPoints(gl);
  if (pointCount < 0) {
    alert('Field to init vertex points.');
    return false;
  }

  const xformMatrix = new Float32Array([
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    0.3, 0.3, 0, 1,
  ]);
  const u_xformMatrix = gl.getUniformLocation(gl.program, 'u_xformMatrix');
  gl.uniformMatrix4fv(u_xformMatrix, false, xformMatrix);

  gl.clearColor(0, 0, 0, 1);
  gl.clear(gl.COLOR_BUFFER_BIT);

  gl.drawArrays(gl.TRIANGLES, 0, pointCount);
}

function initVertexPoints(gl) {
  // 定义顶点坐标数据
  const vertices = new Float32Array([
    0.0, 0.5,
    0.5, 0.0,
    0.0, -0.5,
  ]);
  // 创建缓存区
  const vertexBuffer = gl.createBuffer();
  if (!vertexBuffer) {
    alert('Field to create buffer.');
    return -1;
  }
  // 绑定缓存区到目标
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  // 向缓存区中填充输入
  gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  // 获取 顶点数据的存储位置
  const a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  if (a_Position < 0) {
    alert('Field to get position');
    return -1;
  }
  // 分配缓存区数据到顶点存储位置
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
  // 激活缓存区
  gl.enableVertexAttribArray(a_Position);
  return Math.ceil(vertices.length / 2);
}